/*
 * PLAY.c
 *
 * Created: 11.11.2012 09:29:27
 *  Author: mariuvi
 */ 

#include <avr/io.h>
#include <avr/delay.h>

#include "PLAY.h"
#include "CAN.h"
#include "DISPLAY.h"
#include "definitions.h"

static uint8_t score;
static uint8_t lives;

typedef enum{
	INIT,
	GOAL,
	PLAY,
	PAUSE,
	VICTORIOUS,
	DEFEATED
}PLAY_states;

void PLAY_init()
{
	//Tell Node 1 and 2 that we're playing
	CAN_message_t msg;
	msg.id = CAN_PLAY_MSG;
	msg.length = 0;
	CAN_message_send(msg);
	
	_delay_ms(10);
	
	msg.id = CAN_LEDS_INIT_MSG;
	CAN_message_send(msg);
	
	//Initialize the display for play
	DISPLAY_play_board_init();
	
	//Initialize timer1 with a 1/1024 clock for score tracking
	BIT_SET(TCCR1B, CS30);
	BIT_CLEAR(TCCR1B, CS31);
	BIT_SET(TCCR1B, CS32);
	TCNT1 = 0;
	
	score = 0;
	lives = 3;
	
}

uint8_t PLAY_play(uint8_t goal, uint8_t buttonPressed)
{
static PLAY_states state = INIT;	
		
	switch(state)
	{
		case INIT:
			PLAY_init();
			state = PLAY;
			break;
		case GOAL:
			lives--;
			
			//Turn off one led on node 1
			CAN_message_t msg;
			msg.id = CAN_LEDS_DEC_MSG;
			msg.length = 0;
			CAN_message_send(msg);
			
			//Check if loss
			if(lives == 0)
			{
				DISPLAY_write_line_center("You lose", 1);
				
				CAN_message_t msg;
				msg.id = CAN_PAUSE_PLAY_MSG;
				msg.length = 0;
				CAN_message_send(msg);
				
				state = DEFEATED;
				break;		
			}
			
			DISPLAY_write_line_center("Legg ballen i utskyteren", 3);
			
			state = PAUSE;		
			break;
		case PAUSE:
			if(buttonPressed)
			{
				DISPLAY_write_line("", 3,0,1);
				
				//Tell the IO-card to resume playing
				CAN_message_t msg;
				msg.id = CAN_PLAY_MSG;
				msg.length = 0;
				CAN_message_send(msg);
				
				state = PLAY;
			}
			break;	
		case PLAY:
				//Updates score, seconds
			if(TCNT1 > 7812)
			{
				score++;
				TCNT1 = 0;
			}
			DISPLAY_playboard_update(lives, score);
			//Check for "goal"
			if(goal)
			{
				state = GOAL;
				break;	
			}				
			//Check if victorious
			if(score == 255)
			{
				DISPLAY_write_line_center("VICTORIOUS!", 1);
				
				CAN_message_t msg;
				msg.id = CAN_PAUSE_PLAY_MSG;
				msg.length = 0;
				CAN_message_send(msg);
				
				state = VICTORIOUS;
				break;
			}
			break;
		case VICTORIOUS:
			//if button pressed, go to MENU
			if(buttonPressed)
			{
				state = INIT;
				return TRUE;
			}
			break;
		case DEFEATED:
			//if button pressed, go to MENU
			if(buttonPressed)
			{
				state = INIT;
				return TRUE;
			}	
			break;			
	}
	return FALSE;
}